import React from "react";
import ReactDOM from "react-dom";
import propTypes from "prop-types";

// render props 模式
// 使用children的方式，父传值给子，，，推荐用法

// 导入图片资源
import img from "./images/cat.jpg"

// 实现模型的复用
class Mouse extends React.Component{
    // 鼠标的位置
    state = {
        x: 0,
        y: 0
    }
    // 鼠标移动事件处理
    handleMouseMove = e => {
        this.setState({
            x: e.clientX,
            y: e.clientY
        })
    }

    // 监听鼠标移动事件
    componentDidMount(){
        window.addEventListener('mousemove', this.handleMouseMove)
    }

    // 推荐：在组件卸载时移除事件绑定
    componentWillUnmount() {
        window.removeEventListener('mousemove', this.handleMouseMove)
    }

    render(){
        return (
            this.props.children(this.state) // 将state状态暴露出去,,通过props的方法
        )
    }
}

// 添加props较验
Mouse.propTypes = {
    children: propTypes.func.isRequired //children为必填项
}

class App extends React.Component{
    render () {
        return (
            <div>
                <h1>render props 模式</h1>
                <Mouse>
                    {
                        mouse => {
                            return (<p>鼠标位置：{mouse.x}, {mouse.y}</p>)
                        }
                    }
                </Mouse>


                {/* 猫抓老鼠的功能 */}
                <Mouse>
                    {
                        mouse => {
                            return (
                                <img 
                                    src={img} 
                                    alt="猫" 
                                    height="10"
                                    width="50"
                                    height="50"
                                    style={{
                                        position: "absolute",
                                        top: mouse.y -25,
                                        left: mouse.x - 25
                                    }} />)
                        }
                    }
                </Mouse>


            </div>
        )
    }
}

ReactDOM.render(<App />, document.getElementById('root'))
